package com.yiyi.credit.manage.abutment.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CcxiSignUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(CcxiSignUtils.class);

    public static String sign(String jsonStr,String privateKey,String account) {
        JSONObject obj =  JSONObject.parseObject(jsonStr);
        obj.put("account",account);
        String signSrc = genSignData(obj);
        return signUpper(signSrc,privateKey);
    }

    /**
     * 生成中诚信待签名串
     *
     * @param
     * @return
     */
    public static String getCcxiSign(String jsonStr,String privateKey,String account) {
        JSONObject obj =  JSONObject.parseObject(jsonStr);
        obj.put("account",account);
        String signSrc = genSignData(obj);
        return signSrc;
    }

    /**
     * 生成待签名串
     *
     * @param
     * @return
     */
    public static String genSignData(JSONObject jsonObject) {
        StringBuffer content = new StringBuffer();

        // 按照key做首字母升序排列
        List<String> keys = new ArrayList<String>(jsonObject.keySet());
        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            // sign 和ip_client 不参与签名
            if ("sign".equals(key)) {
                continue;
            }else if ("appId".equals(key)){
                continue;
            }
            String value = (String) jsonObject.getString(key);
            // 空串不参与签名
            if (StringUtils.isEmpty(value)) {
                continue;
            }
            content.append(key + value);

        }
        String signSrc = content.toString();
        return signSrc;
    }

    public static String signUpper(String signSrc, String key) {
        String sign =SecurityUtils.md5(signSrc +key).toUpperCase();
        LOGGER.info("中诚信最终待签串:{} sign:{}",signSrc +key,sign);
        return sign;
    }

}
